﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mappit {
    public abstract class Command {
        public abstract void Execute();
        public abstract void Undo();
        public bool CanUndo() { return true; }
    }

    public class CommandStack {
        private List<Command> undo_list_ = new List<Command>();
        private List<Command> redo_list_ = new List<Command>();
        public void Execute(Command cmd) {
            cmd.Execute();
            if (cmd.CanUndo()) {
                undo_list_.Add(cmd);
                redo_list_.Clear();
            } else {
                undo_list_.Clear();
                redo_list_.Clear();
            }
        }
        private Command TransferCommand(List<Command> from_list, List<Command> to_list) {
            if(from_list.Count == 0) {
                return null;
            }
            Command cmd = from_list.Last();
            from_list.RemoveAt(from_list.Count - 1);
            to_list.Add(cmd);
            return cmd;
        }
        public void Undo() {
            Command cmd = TransferCommand(undo_list_, redo_list_);
            if(cmd != null)
                cmd.Undo();
        }
        public void Redo() {
            Command cmd = TransferCommand(redo_list_, undo_list_);
            if (cmd != null)
                cmd.Execute();
        }
        public bool CanUndo() {
            return undo_list_.Count > 0;
        }
        public bool CanRedo() {
            return redo_list_.Count > 0;
        }
    }
}
